import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_ExamBean.dart';
import 'package:flutter_learn_vi/src/bean/bean_day_stat.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_page.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_details_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_enum.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

import '../../common/user_helper.dart';
import '../../face/face_detector_view.dart';
import '../../utils/time_date_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 4/4/21.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///

///考试详情
class MineMyExamDetailsPage extends StatefulWidget {
  final BeanExamBean examBean;

  const MineMyExamDetailsPage({Key key, this.examBean}) : super(key: key);

  @override
  _MineMyExamDetailsPageState createState() => _MineMyExamDetailsPageState();
}

class _MineMyExamDetailsPageState extends State<MineMyExamDetailsPage> {
  @override
  void initState() {
    super.initState();
    _loadingMyExam();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("考试详情"),
      ),
      backgroundColor: Colors.white,
      body: Container(padding: EdgeInsets.all(12), child: buildColumn()),
    );
  }

  Widget buildColumn() {
    if (_isLoading) {
      return Center(
        child: LoadingPage(),
      );
    }
    if (_beanExamBean == null) {
      return Center(
        child: NoDataWidget(
          text: "暂无详情",
          clickCallBack: () {
            _isLoading = true;
            setState(() {});
            _loadingMyExam();
          },
        ),
      );
    }

    //考试次数
    int examNumber = _beanExamBean.examNumber;
    //用户已参与的考试次数
    // int userExamNumber = _beanList.length;
    int openExercise = _beanExamBean.openExercise;
    String exercise = '';
    if (openExercise == 1) {
      exercise = '请注意：考试期间不可以参与练习模式';
    }
    return Stack(
      children: [
        Positioned.fill(
            child: NestedScrollView(
          body: buildListView(),
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          height: 16,
                          width: 3,
                          decoration: BoxDecoration(
                              color: Colors.green,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(4))),
                          margin: EdgeInsets.only(right: 10, top: 4),
                        ),
                        Expanded(
                          child: Text(
                            "${_beanExamBean.examTitle}",
                            style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 16,
                                color: Color(0xff444444)),
                          ),
                        )
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 14, top: 12),
                      child: Text(
                        "开始考试时间 ${_beanExamBean.openTime}",
                        style: TextStyle(
                          color: Color(0xff888888),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 14, top: 6),
                      child: Text(
                        "结束考试时间 ${_beanExamBean.closeTime}",
                        style: TextStyle(
                          color: Color(0xff888888),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 14, top: 6),
                      child: Text(
                        "本考试可参与 $examNumber次",
                        style: TextStyle(
                          color: Color(0xff888888),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 14, top: 6),
                      child: Row(
                        children: [
                          Text(
                            "考试时间 ${_beanExamBean.examTim} 分钟",
                            style: TextStyle(
                              color: Color(0xff888888),
                            ),
                          ),
                          Text(
                            "及格分数 ${_beanExamBean.examPercent} 分",
                            style: TextStyle(
                              color: Color(0xff888888),
                            ),
                          )
                        ],
                      ),
                    ),
                    exercise.isNotEmpty
                        ? Container(
                            margin: EdgeInsets.only(left: 14, top: 6),
                            child: Text(
                              exercise,
                              style: TextStyle(
                                color: Colors.red,
                              ),
                            ),
                          )
                        : SizedBox(),
                    buildExamRuleContentWidget(),
                    buildExamTipsContainer(),
                  ],
                ),
              )
            ];
          },
        )),
        Positioned(
          child: buildStartExamButton(),
          left: 0,
          right: 0,
          bottom: 44,
        ),
      ],
    );
  }

  BeanExamBean _beanExamBean;
  bool _isLoading = true;

  ///加载考试详情
  void _loadingMyExam() async {
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.pcTestExamDetails + "/${widget.examBean.id}");
    if (statisRresponseInfo.success) {
      _beanExamBean = BeanExamBean.fromMap(statisRresponseInfo.data);
    } else {
      Get.defaultDialog(
          title: "提示",
          content: Text(statisRresponseInfo.message),
          textCancel: "退出",
          onCancel: () {
            Get.back();
          });
      return;
    }
    //获取的的答题
    await _getTopicHistoryist();

    _isLoading = false;
    if (mounted) {
      setState(() {});
    }
  }

  List<BeanDayStat> _beanList = [];

  ///查询我的答题记录
  Future<List<BeanDayStat>> _getTopicHistoryist() async {
    Map<String, dynamic> monthMap = {
      "queryExamUid": _beanExamBean.examUid,
      "sort": "TIMES",
      "pageName": "MineMyExamDetailsPage",
    };

    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.myMyScoreQuestionRecoderUrl, jsonMap: monthMap);
    _beanList = [];
    _isRefreshLoading = false;
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data['list'];
      list.forEach((element) {
        _beanList.add(BeanDayStat.fromMap(element));
      });
      if (mounted) {
        setState(() {});
      }
      return _beanList;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      if (mounted) {
        setState(() {});
      }
      return _beanList;
    }
  }

  buildExamRuleContentWidget() {
    String ruleStr = _beanExamBean.ruleStr;
    if (ruleStr == null || ruleStr.isEmpty) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(left: 14, top: 20),
      child: Text(ruleStr),
    );
  }

  buildExamRuleContainer() {
    int totalNumber = _beanExamBean.topicNumber;
    int ruleSign = (_beanExamBean.ruleSign * 1.0 / 100 * totalNumber).toInt();
    int ruleJudge = (_beanExamBean.ruleJudge * 1.0 / 100 * totalNumber).toInt();
    int ruleMult = (_beanExamBean.ruleMult * 1.0 / 100 * totalNumber).toInt();
    int ruleGap = (_beanExamBean.ruleGap * 1.0 / 100 * totalNumber).toInt();
    return Container(
      margin: EdgeInsets.only(left: 14, top: 20),
      child: RichText(
        text: TextSpan(children: <InlineSpan>[
          TextSpan(
              text: '本次考试总共',
              style: TextStyle(
                color: Color(0xff888888),
              )),
          TextSpan(
              text: '${_beanExamBean.topicNumber}题，',
              style: TextStyle(color: Colors.blueGrey)),
          TextSpan(
              text: '题型包含 ',
              style: TextStyle(
                color: Color(0xff888888),
              )),
          TextSpan(text: '单选题', style: TextStyle(color: Colors.blueGrey)),
          TextSpan(
              text: '$ruleSign题、', style: TextStyle(color: Colors.blueGrey)),
          TextSpan(text: '多选题', style: TextStyle(color: Colors.blueGrey)),
          TextSpan(
              text: '$ruleMult题、', style: TextStyle(color: Colors.blueGrey)),
          TextSpan(text: '判断题', style: TextStyle(color: Colors.blueGrey)),
          TextSpan(
              text: '$ruleJudge题、', style: TextStyle(color: Colors.blueGrey)),
          TextSpan(text: '填空题', style: TextStyle(color: Colors.blueGrey)),
          TextSpan(
              text: '$ruleGap题。', style: TextStyle(color: Colors.blueGrey)),
        ]),
      ),
    );
  }

  buildExamTipsContainer() {
    return Container(
      margin: EdgeInsets.only(left: 14, top: 6),
      child: Text(
        "请注意：超出考试时间后将不可再进入考试",
        style: TextStyle(
          fontSize: 12,
          color: Colors.red,
        ),
      ),
    );
  }

  buildStartExamButton() {
    //考试次数
    int examNumber = _beanExamBean.examNumber;
    //用户已参与的考试次数
    int userExamNumber = _beanList.length;
    LogUtils.e("考试次数 $examNumber 用户已参与的考试次数 $userExamNumber");
    BeanDayStat beanDayStat;
    double obtainScore = 0.0;
    if (userExamNumber > 0) {
      beanDayStat = _beanList[_beanList.length - 1];
      obtainScore = beanDayStat.obtainScore / 10;

      if (obtainScore >= _beanExamBean.examPercent) {}
    }
    return Container(
      margin: EdgeInsets.only(left: 14, top: 6),
      width: double.infinity,
      alignment: Alignment.centerLeft,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // Text(
          //   "已参与$userExamNumber次考试 最近一次的考试成绩如下",
          //   style: TextStyle(color: textColor),
          // ),
          // userExamNumber > 0
          //     ? Container(
          //         padding: EdgeInsets.all(10),
          //         margin: EdgeInsets.only(top: 6),
          //         decoration: BoxDecoration(
          //             borderRadius: BorderRadius.all(Radius.circular(4)),
          //             border: Border.all(color: textColor)),
          //         child: Column(
          //           crossAxisAlignment: CrossAxisAlignment.start,
          //           mainAxisSize: MainAxisSize.min,
          //           children: [
          //             Text("最终得分：${obtainScore} 分"),
          //             Text(
          //                 "用时：${DurationUtils.fromatMil(beanDayStat.answerTime)}"),
          //           ],
          //         ),
          //       )
          //     : Container(),
          // SizedBox(
          //   height: 40,
          // ),
          userExamNumber >= examNumber ? Container() : buildButtonRow(),
        ],
      ),
    );
  }

  bool _isRefreshLoading = false;

  Widget buildButtonRow() {
    if (_isRefreshLoading) {
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        LoadingWidget(
          text: "正在刷新考试结果中",
        )
      ]);
    }
    if (_beanExamBean.isClose == 1) {
      return Container(
        child: Text("考试已结束"),
      );
    }

    ///考试期间 练习模式是否开启 0 开启  1 关闭',
    int openExercise = _beanExamBean.openExercise;
    bool showExercise = true;
    if (openExercise == 1) {
      DateTime now = DateTime.now();
      String openTimeStr = _beanExamBean.openTime;
      String closeTimeStr = _beanExamBean.closeTime;

      DateTime openTime =
          TimeViDateUtils.getDateTimeByStr(dateStr: openTimeStr);
      DateTime closeTime =
          TimeViDateUtils.getDateTimeByStr(dateStr: closeTimeStr);

      if (now.isAfter(openTime) && now.isBefore(closeTime)) {
        showExercise = false;
      }
    }
    //是否结束 超出时间的为结束的 0 未结束  1已结束
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        ElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.resolveWith((states) {
                //设置按下时的背景颜色
                if (showExercise) {
                  return Colors.blue;
                }
                //默认不使用背景颜色
                return Colors.grey;
              }),
            ),
            onPressed: () {
              if (!showExercise) {
                Get.defaultDialog(
                  radius: 4,
                  title: "提示",
                  content: Container(
                    constraints: BoxConstraints(maxHeight: 600),
                    child: SingleChildScrollView(
                      child: Text("考试期间不可参与练习模式"),
                    ),
                  ),
                  confirm: Container(
                    alignment: Alignment.center,
                    child: TextButton(
                      onPressed: () {
                        Get.back(result: true);
                      },
                      child: Text(
                        "确认",
                        style: TextStyle(color: Colors.blue),
                      ),
                    ),
                    width: 100,
                  ),
                );
                return;
              }
              _stopTimer();
              NavigatorUtils.pushPage(
                context,
                TopicDetilsPage(
                  pageTitle: "练习模式",
                  examBean: _beanExamBean,
                  topicEnum: TopicEnum.pcExam,
                  categoryOne: "COMPUTER_TEST",
                  categoryTwo: "COMPUTER_TEST_SUB",
                  examType: "N",
                ),
                callback: (value) {
                  LogUtils.e("刷新考试结果");
                  //查询考试结果
                  _startTimer();
                },
              );
            },
            child: Text("练习模式")),
        SizedBox(
          width: 33,
        ),
        buildStartElevatedButton(),
      ],
    );
  }

  //点击了开始考试按钮
  bool clickStartButton = false;

  ElevatedButton buildStartElevatedButton() {
    if (_beanExamBean.isOpen == 1) {
      //0 开启  1 关闭',
      return ElevatedButton(
        onPressed: () {},
        child: Text(
          "考试未开启",
          style: TextStyle(color: Colors.red),
        ),
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Color(0xffeeeeee)), //背景颜色
        ),
      );
    }
    return ElevatedButton(
        onPressed: () async {
          dynamic reault = await Get.defaultDialog(
              radius: 4,
              title: "温馨提示",
              content: Container(
                child: Text("确定开始考试吗？${_getExamTips()}"),
              ),
              onConfirm: () {
                Get.back(result: true);
              },
              textCancel: "取消",
              textConfirm: "开始考试");

          if (reault == null || !reault) {
            debugPrint("取消考试");
            return false;
          }
          bool isShowFaceCheck = UserHelper.getInstance.isShowFaceCheck();
          if (isShowFaceCheck) {
            if (_beanExamBean.faceRecognition == "on") {
              //开启人脸识别一下
              dynamic result = await Get.defaultDialog(
                  title: "提示",
                  content: Text("本考试需要人脸识别认证"),
                  textCancel: "取消",
                  textConfirm: "去认证",
                  radius: 10,
                  onConfirm: () {
                    Get.back(result: true);
                  });
              if (result == null || !result) {
                debugPrint("未选择去认证");
                ToastUtils.showToast("需要人脸认证后才能参加考试");
                clickStartButton = false;
                setState(() {});
                return false;
              }
              dynamic faceResult = await Get.to(() => FaceDetectorView(
                    key: UniqueKey(),
                  ));
              if (faceResult == null || faceResult.toString().isEmpty) {
                ToastUtils.showToast("需要人脸认证后才能参加考试");
                clickStartButton = false;
                setState(() {});
                return false;
              }
              //比对一下当前的人脸数据
              ResponseInfo statisRresponseInfo = await DioUtils.instance
                  .postRequest(
                      url: HttpHelper.compareFaceUrl,
                      encrypt: false,
                      jsonMap: {
                    "examUid": _beanExamBean.examUid,
                    "faceType": "exam",
                    "faceImageUrl": faceResult.toString(),
                  });

              if (statisRresponseInfo.success) {
                //识别成功 继续播放
                debugPrint("人脸识别成功 继续考试");
              } else {
                dynamic result = await Get.defaultDialog(
                    radius: 10,
                    title: "人脸信息核定失败",
                    content: Text(statisRresponseInfo.message ?? "网络请求错误"),
                    textCancel: "关闭");
                clickStartButton = false;
                setState(() {});
                return false;
              }
            }
          } else {
            debugPrint("人脸识别权限关闭");
          }

          _stopTimer();
          NavigatorUtils.pushPage(
            context,
            TopicDetilsPage(
              pageTitle: "我的考试",
              examUid: _beanExamBean.examUid,
              examBean: _beanExamBean,
              topicEnum: TopicEnum.pcExam,
              categoryOne: "COMPUTER_TEST",
              categoryTwo: "COMPUTER_TEST_SUB",
              examType: "Y",
            ),
            callback: (value) {
              LogUtils.e("刷新考试结果");
              setState(() {
                _isRefreshLoading = true;
              });
              //查询考试结果
              _startTimer();
            },
          );
        },
        child: Text("开始考试"));
  }

  String _getExamTips() {
    //考试次数
    int examNumber = _beanExamBean.examNumber;
    //模式
    String testCountModelSr = "";
    int testCountModel = _beanExamBean.testCountModel;
    //1每日;2每月;3本次考试; 4不限次数
    if (testCountModel == 1) {
      testCountModelSr = "本考试 每日可参与$examNumber次";
    } else if (testCountModel == 2) {
      testCountModelSr = "本考试 每月可参与$examNumber次";
    } else if (testCountModel == 3) {
      testCountModelSr = "本考试 可参与$examNumber次";
    } else {
      testCountModelSr = "本次考试不限次数";
    }
    return testCountModelSr;
  }

  Timer _timer;

  void _startTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      _getTopicHistoryist();
    });
  }

  void _stopTimer() {
    if (_timer != null && _timer.isActive) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    _stopTimer();
  }

  buildListView() {
    return Container(
      padding: EdgeInsets.only(top: 10, left: 10, right: 10),
      child: ListView.builder(
        itemCount: _beanList.length,
        itemBuilder: (BuildContext context, int index) {
          BeanDayStat dayStat = _beanList[index];
          return createExamItem(dayStat);
        },
      ),
    );
  }

  Widget createExamItem(BeanDayStat item) {
    int answerTime = 0;
    num score = 0;
    String createTime = '刚刚';
    answerTime = item.answerTime;
    score = item.obtainScore / 10 / item.extryScore;
    createTime = item.createTime;

    int min = answerTime ~/ 60;
    int second = (answerTime % 60);
    String minStr = min > 9 ? "$min分" : "0$min分";
    String secondStr = second > 9 ? "$second秒" : "0$second秒";

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Image.asset(
              "assets/images/2.0x/exam_icon_2.png",
              width: 16,
            ),
            SizedBox(
              width: 12,
            ),
            Expanded(
              child: Text(
                "考试时间 $createTime",
                style: TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
              ),
            ),
          ],
        ),
        Container(
          margin: EdgeInsets.only(left: 28, top: 4),
          child: Row(
            children: [
              Text(
                "用时 $minStr $secondStr ",
                style: TextStyle(fontWeight: FontWeight.normal, fontSize: 12),
              ),
              Expanded(
                child: Text(
                  "得分 $score 分",
                  textAlign: TextAlign.end,
                  style: TextStyle(fontWeight: FontWeight.normal, fontSize: 12),
                ),
              )
            ],
          ),
        ),
        buildIntegerScoreContainer(item),
        SizedBox(height: 16),
      ],
    );
  }

  Widget buildIntegerScoreContainer(BeanDayStat beanDayStat) {
    if (beanDayStat.integerRemark.isEmpty) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(left: 28, top: 8),
      child: Text(
        "积分${beanDayStat.integerScore}分； ${beanDayStat.integerRemark}",
        style: TextStyle(
          fontSize: 12,
          color: Colors.grey,
        ),
      ),
    );
  }
}
